import {Component, EventEmitter, OnInit, Output, ViewChild} from '@angular/core';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import {NzMessageService} from 'ng-zorro-antd/message';
import {DepartmentService} from '../../service/department.service';
import {SharedModule} from '../shared.module';
import {DepartmentForm} from '../../types/req/DepartmentForm';
import {MODAL_WIDTH} from '../../const'
import {EnterpriseSelectorComponent} from '../enterprise/enterprise-selector.component';
import {DepartmentSelectorComponent} from '../department/department-selector.component';

@Component({
  selector: 'department-add',
  imports: [
    EnterpriseSelectorComponent,
    DepartmentSelectorComponent,
    SharedModule
  ],
  templateUrl: './department-add.component.html',
  standalone: true
})
export class DepartmentAddComponent implements OnInit {
  departmentToSave:DepartmentForm = {};
  departmentForm!: FormGroup;
  isVisible: boolean = false
  saveLoading: boolean = false
  title: string = '新增部门信息'
  modalWidth: string = MODAL_WIDTH

  @ViewChild(EnterpriseSelectorComponent, { static: false }) enterpriseSelectorComponent!: EnterpriseSelectorComponent;
  @ViewChild(DepartmentSelectorComponent, { static: false }) departmentSelectorComponent!: DepartmentSelectorComponent;

  @Output() addedEvent = new EventEmitter<boolean>();

  constructor(
    private fb: FormBuilder,
    private message: NzMessageService,
    private departmentService: DepartmentService
  ) {}

  ngOnInit(): void {
    this.departmentForm = this.fb.group({
      enterpriseId: [0],
      enterpriseName: ['', [Validators.required]],
      departmentName: ['', [Validators.required]],
      departmentDescription: [''],
      departmentId: [0],
      parentDepartmentName: [''],
    })
  }

  onSave() {
    try {
      this.saveLoading = true
      for (const i in this.departmentForm.controls) {
        this.departmentForm.controls[i].markAsDirty();
        this.departmentForm.controls[i].updateValueAndValidity();
      }
      if (!this.departmentForm.valid) {
        this.saveLoading = false
        return
      }
      this.departmentService.save(Object.assign(this.departmentToSave, this.departmentForm.value)).subscribe({
        next: (resp) => {
          if (!resp || resp.code !== 1) {
            this.message.error(resp && resp.msg ? resp.msg : '操作异常')
            return
          }
          this.message.success("保存成功")
          this.onBack(true)
        },
        complete: () => {
          this.saveLoading = false
        }
      })
    } catch (e) {
      console.log('获取数据异常', e)
    }
  }

  onReset() {
    this.title = '新增部门信息'.slice()
    this.departmentForm.reset()
  }

  onBack(addedFlag=false) {
    this.isVisible = false
    this.addedEvent.emit(addedFlag);
  }

  display(id: number) {
    this.isVisible = true
    if (id) {
      this.title = '修改部门信息'
      this.saveLoading = true
      this.departmentService.findById(id).subscribe({
        next: (resp) => {
          if (resp && resp.code === 1 && resp.data) {
            this.departmentToSave = resp.data
            this.departmentForm.patchValue(this.departmentToSave);
          }
        },
        complete: () => {
          this.saveLoading = false
        }
      })
    } else {
      this.onReset()
    }
  }

  findEnterprise() {
    this.enterpriseSelectorComponent.display()
  }

  handleEnterpriseSelectedEvent(selectedEnterprise: { enterpriseId?: number; enterpriseName?: string; }) {
    if (selectedEnterprise && 'enterpriseId' in selectedEnterprise) {
      this.departmentForm.patchValue(selectedEnterprise);
    }
  }

  findDepartment() {
    this.departmentSelectorComponent.display()
  }

  handleDepartmentSelectedEvent(selectedDepartment: { departmentId?: number; parentDepartmentName?: string; }) {
    if (selectedDepartment && 'departmentId' in selectedDepartment) {
      this.departmentForm.patchValue(selectedDepartment);
    }
  }
}
